<template>
	<view class="fuel-nearby-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">就近加油</view>
			<view class="navbar-right">
				<uni-icons type="more-filled" size="20" @click="showMoreOptions"></uni-icons>
				<uni-icons type="location-filled" size="20" @click="manualRelocation" :color="currentLocation && currentLocation.isDefault ? '#ff4757' : '#007AFF'"></uni-icons>
			</view>
		</view>
		
		<!-- 搜索栏作为页面头部 -->
		<view class="search-header">
			<view class="search-container">
				<uni-search-bar 
					@input="handleInput" 
					@confirm="handleSearch"
					@search="handleSearch"
					placeholder="搜索加油站"
					cancelButton="none"
					radius="8"
					bgColor="#f5f5f5"
					confirmType="search"
				></uni-search-bar>
			</view>
		</view>
		
		<!-- 位置信息栏 -->
		<view v-if="currentLocation" class="location-info-bar">
			<view class="location-content">
				<view class="location-left">
					<uni-icons :type="currentLocation.isDefault ? 'location' : 'location-filled'" size="16" :color="currentLocation.isDefault ? '#ff4757' : '#007AFF'"></uni-icons>
					<text class="location-text">
						{{ currentLocation.isDefault ? '默认位置' : '当前位置' }}：{{ currentLocation.description || currentLocation.name || '已定位' }}
					</text>
				</view>
				<view class="location-actions">
					<text class="action-btn" @click="manualRelocation">重新定位</text>
					<text class="action-btn" @click="manualInputLocation">手动输入</text>
					<view class="data-source-icon" @click="toggleDataSource" @longpress="showDataSourceHint">
						<uni-icons :type="useRealData ? 'checkmarkempty' : 'closeempty'" size="16" :color="useRealData ? '#007AFF' : '#999'"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 模式切换 -->
		<view class="control-section">
			<view class="mode-switch">
				<view class="switch-container">
					<view class="switch-btn" :class="{ active: !isMapMode }" @click="switchToListMode">列表模式</view>
					<view class="switch-btn" :class="{ active: isMapMode }" @click="switchToMapMode">地图模式</view>
				</view>
			</view>
		</view>
		
		<!-- 筛选选项 -->
		<view class="filter-section" v-if="!isMapMode">
			<view class="filter-item" @click="showFilterOptions">
				<text class="filter-text">排序</text>
				<uni-icons type="down" size="12"></uni-icons>
			</view>
		</view>
		
		<!-- 搜索状态指示器 -->
		<view v-if="isSearching && searchKeyword && !isMapMode" class="search-status">
			<text class="search-status-text">搜索关键词："{{ searchKeyword }}"</text>
		</view>
		
		<!-- 地图模式 -->
		<view v-if="isMapMode" class="map-container">
			<RealMap 
				:currentLocation="currentLocation"
				:gasStations="gasStations"
				@request-location="getCurrentLocation"
			/>
		</view>
		
		<!-- 列表模式 -->
		<view v-else class="station-list">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="gasStations.length === 0" class="empty-container">
				<text class="empty-text">
					{{ isSearching ? `未找到包含"${searchKeyword}"的加油站` : '暂无加油站数据' }}
				</text>
			</view>
			
			<!-- 加油站列表 -->
			<view 
				v-else
				class="station-item" 
				v-for="(station, index) in gasStations" 
				:key="index"
				@click="selectStation(station)"
			>
						<view class="station-image">
			<image :src="station.image" mode="aspectFill" class="station-img"></image>
		</view>
				<view class="station-info">
					<view class="station-name">{{ station.name }}</view>
					<view class="station-price" v-if="station.discount && station.discount !== '暂无优惠'">
						<text class="discount-text">{{ station.discount }}</text>
					</view>
					<view class="station-address">{{ station.address }}</view>
					<view class="station-phone">{{ station.phone }}</view>
					<view class="station-time">{{ station.week }}</view>
				</view>
				<view class="station-actions">
					<view class="distance">{{ station.distance }}</view>
					<view class="navigation-btn" @click.stop="navigateToStation(station)">
						<uni-icons type="paperplane" size="16" color="#007AFF"></uni-icons>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import uniSearchBar from '@dcloudio/uni-ui/lib/uni-search-bar/uni-search-bar.vue';
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue';
	import RealMap from './RealMap.vue';
	import { gasStationApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniSearchBar,
			uniIcons,
			uniLoadMore,
			RealMap
		},
		data() {
			return {
				gasStations: [],
				loading: false,
				searchKeyword: '',
				currentLocation: null,
				isSearching: false,
				isMapMode: false,
				useRealData: true, // 是否使用真实数据
				selectedStation: null,
				searchTimer: null,
				loadingText: {
					contentdown: '上拉显示更多',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				}
			};
		},
		computed: {
			// 判断是否为真实位置
			isRealLocation() {
				if (!this.currentLocation) return false;
				const defaultLat = 39.9042;
				const defaultLng = 116.4074;
				const latDiff = Math.abs(this.currentLocation.latitude - defaultLat);
				const lngDiff = Math.abs(this.currentLocation.longitude - defaultLng);
				return latDiff > 0.001 || lngDiff > 0.001;
			}
		},
		onLoad() {
			this.initLocation();
		},
		methods: {
			// 初始化定位
			async initLocation() {
				try {
					console.log('开始初始化定位...');
					
					// 添加超时保护
					const locationPromise = this.getCurrentLocation();
					const timeoutPromise = new Promise((_, reject) => {
						setTimeout(() => reject(new Error('定位超时')), 15000);
					});
					
					await Promise.race([locationPromise, timeoutPromise]);
					await this.loadGasStations();
				} catch (error) {
					console.error('初始化失败:', error);
					this.useDefaultLocation();
					await this.loadGasStations();
				}
			},
			
			// 获取当前位置
			async getCurrentLocation() {
				try {
					uni.showLoading({
						title: '定位中...'
					});
					
					// 使用uni-app的定位API
					const locationResult = await new Promise((resolve, reject) => {
						uni.getLocation({
							type: 'gcj02',
							success: resolve,
							fail: reject
						});
					});
					
					console.log('定位成功:', locationResult);
					
					this.currentLocation = {
						latitude: locationResult.latitude,
						longitude: locationResult.longitude,
						description: '当前位置',
						isDefault: false
					};
					
					// 获取地址信息
					await this.getAddressFromLocation(locationResult.latitude, locationResult.longitude);
					
					uni.hideLoading();
					return this.currentLocation;
				} catch (error) {
					console.error('定位失败:', error);
					uni.hideLoading();
					throw error;
				}
			},
			
			// 手动重新定位
			async manualRelocation() {
				// 先检查定位权限
				const hasPermission = await this.checkLocationPermission();
				
				if (!hasPermission) {
					uni.showModal({
						title: '定位权限',
						content: '需要定位权限才能获取您的位置。请在浏览器设置中允许定位权限，然后重试。',
						confirmText: '去设置',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.showLocationSettings();
							}
						}
					});
					return;
				}
				
				uni.showModal({
					title: '重新定位',
					content: '是否要重新获取当前位置？',
					success: async (res) => {
						if (res.confirm) {
							await this.getCurrentLocation();
						}
					}
				});
			},
			
			// 检查定位权限
			async checkLocationPermission() {
				return new Promise((resolve) => {
					if (navigator && navigator.permissions) {
						navigator.permissions.query({ name: 'geolocation' }).then((result) => {
							console.log('定位权限状态:', result.state);
							resolve(result.state === 'granted');
						}).catch(() => {
							// 如果不支持permissions API，尝试直接定位
							resolve(true);
						});
					} else {
						// 不支持permissions API，假设有权限
						resolve(true);
					}
				});
			},
			
			// 显示定位设置指导
			showLocationSettings() {
				uni.showModal({
					title: '定位设置指导',
					content: '1. 点击地址栏左侧的锁定图标\n2. 找到"位置信息"选项\n3. 选择"允许"\n4. 刷新页面后重试',
					showCancel: false,
					confirmText: '知道了'
				});
			},
			
			// 手动输入位置
			manualInputLocation() {
				uni.showModal({
					title: '手动输入位置',
					content: '请输入您的位置（如：白骅街），系统将自动搜索该位置附近的加油站',
					editable: true,
					placeholderText: '请输入位置名称',
					success: async (res) => {
						if (res.confirm && res.content) {
							await this.searchLocationByName(res.content);
						}
					}
				});
			},
			
			// 根据位置名称搜索
			async searchLocationByName(locationName) {
				try {
					uni.showLoading({ title: '搜索位置中...' });
					
					// 郑州市常见位置的坐标（与加油站坐标匹配）
					const locationDatabase = {
						'白骅街': { 
							latitude: 34.827162, 
							longitude: 113.55295, 
							name: '白骅街',
							area: '梧桐街道',
							description: '郑州市高新区梧桐街道白骅街'
						},
						'白华街': { 
							latitude: 34.829162, 
							longitude: 113.55495, 
							name: '白华街',
							area: '梧桐街道',
							description: '郑州市高新区梧桐街道白华街'
						},
						'百花街': { 
							latitude: 34.831162, 
							longitude: 113.55695, 
							name: '百花街',
							area: '梧桐街道',
							description: '郑州市高新区梧桐街道百花街'
						},
						'梧桐街': { 
							latitude: 34.833162, 
							longitude: 113.55895, 
							name: '梧桐街',
							area: '梧桐街道',
							description: '郑州市高新区梧桐街道'
						},
						'二七广场': { 
							latitude: 34.835162, 
							longitude: 113.56095, 
							name: '二七广场',
							area: '二七区',
							description: '郑州市二七区二七广场'
						},
						'郑州东站': { 
							latitude: 34.827162, 
							longitude: 113.55295, 
							name: '郑州东站',
							area: '郑东新区',
							description: '郑州市郑东新区郑州东站'
						}
					};
					
					// 模糊匹配位置名称
					let matchedLocation = null;
					for (const [key, location] of Object.entries(locationDatabase)) {
						if (locationName.includes(key) || key.includes(locationName)) {
							matchedLocation = location;
							break;
						}
					}
					
					// 如果没有匹配到，使用白骅街作为默认
					if (!matchedLocation) {
						matchedLocation = locationDatabase['白骅街'];
						uni.showToast({
							title: '未找到精确位置，使用白骅街',
							icon: 'none',
							duration: 2000
						});
					}
					
					this.currentLocation = {
						latitude: matchedLocation.latitude,
						longitude: matchedLocation.longitude,
						isDefault: false,
						accuracy: 50, // 手动输入的精度
						name: matchedLocation.name,
						area: matchedLocation.area,
						description: matchedLocation.description
					};
					
					uni.showToast({
						title: `已定位到${matchedLocation.description}`,
						icon: 'success',
						duration: 2000
					});
					
					// 加载加油站数据
					await this.loadGasStations();
					
				} catch (error) {
					console.error('搜索位置失败:', error);
					uni.showToast({
						title: '搜索位置失败',
						icon: 'none',
						duration: 2000
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 使用默认位置
			useDefaultLocation() {
				this.currentLocation = {
					latitude: 34.827162, // 郑州地区加油站坐标（与数据库中的坐标匹配）
					longitude: 113.55295
				};
				console.log('使用默认位置:', this.currentLocation);
			},
			
			// 移动到当前位置
			moveToCurrentLocation() {
				if (this.currentLocation) {
					uni.showToast({
						title: '已移动到当前位置',
						icon: 'success'
					});
				} else {
					this.getCurrentLocation();
				}
			},
			
			// 切换数据源
			async toggleDataSource() {
				this.useRealData = !this.useRealData;
				uni.setStorageSync('useRealData', this.useRealData);
				
				uni.showToast({
					title: `已切换到${this.useRealData ? '真实' : '模拟'}数据`,
					icon: 'success',
					duration: 2000
				});
				
				// 重新加载数据
				if (this.currentLocation) {
					await this.loadGasStations();
				}
			},
			
			// 显示数据源提示
			showDataSourceHint() {
				const status = this.useRealData ? '真实数据' : '模拟数据';
				uni.showModal({
					title: '数据源说明',
					content: `当前使用${status}\n\n点击图标可切换数据源\n长按查看此说明`,
					showCancel: false,
					confirmText: '知道了'
				});
			},
			
			// 加载加油站数据
			async loadGasStations() {
				try {
					this.loading = true;
					
					// 检查当前位置
					if (!this.currentLocation) {
						console.error('当前位置未获取，无法加载加油站');
						uni.showToast({
							title: '位置信息获取失败',
							icon: 'none'
						});
						return;
					}
					
					console.log('开始加载加油站，当前位置:', this.currentLocation);
					console.log('纬度类型:', typeof this.currentLocation.latitude, '值:', this.currentLocation.latitude);
					console.log('经度类型:', typeof this.currentLocation.longitude, '值:', this.currentLocation.longitude);
					
					// 确保坐标是数字类型
					const lat = parseFloat(this.currentLocation.latitude);
					const lng = parseFloat(this.currentLocation.longitude);
					
					if (isNaN(lat) || isNaN(lng)) {
						console.error('坐标转换失败:', { lat, lng });
						uni.showToast({
							title: '坐标信息错误',
							icon: 'none'
						});
						return;
					}
					
					console.log('转换后的坐标:', { lat, lng });
					
					const params = {
						latitude: lat,
						longitude: lng,
						useRealAPI: this.useRealData
					};
					
					console.log('加载加油站参数:', params);
					
					// 修复：传递独立参数而不是对象
					const result = await gasStationApi.getNearbyGasStations(lat, lng, 5000);
					
					console.log('加油站API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 根据你的request.js，API函数直接接收到{code, msg, data}格式
					if (result.code === 200) {
						// 转换后端数据为前端期望的格式
						this.gasStations = this.convertBackendData(result.data);
						console.log('加载到加油站数据:', this.gasStations.length, '个');
						console.log('加油站数据详情:', this.gasStations);
						
						// 显示数据源信息
						const dataType = this.useRealData ? '真实' : '模拟';
						console.log(`使用${dataType}数据源`);
						
						// 检查地图模式下的标记显示
						if (this.isMapMode) {
							console.log('当前为地图模式，加油站数据已更新');
							console.log('传递给地图组件的加油站数量:', this.gasStations.length);
						}
					} else {
						console.error('加载加油站失败:', result.msg);
						uni.showToast({
							title: result.msg || '加载失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载加油站失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
						},
			
			// 转换后端数据为前端期望的格式
			convertBackendData(backendData) {
				console.log('开始转换后端数据，原始数据:', backendData);
				
				if (!backendData || !Array.isArray(backendData)) {
					console.warn('后端数据为空或不是数组');
					return [];
				}
				
				const convertedData = backendData.map((station, index) => {
					// 根据后端数据库字段进行转换
					const converted = {
						id: station.gasStationId || station.id,
						name: station.name || '未知加油站',
						address: station.address || '地址未知',
						image: station.img || '/static/gas-station-default.png',
						phone: station.phone || '暂无电话',
						week: station.week || '营业时间未知',
						message: station.message || '暂无优惠',
						longitude: station.longitude,
						latitude: station.latitude,
						// 前端期望的字段
						price: '', // 不显示价格，点击进去查看
						discount: station.message || '暂无优惠',
						distance: station.distance ? `${station.distance.toFixed(1)}km` : '距离未知'
					};
					
					console.log(`第${index + 1}个加油站转换:`, {
						原始: station,
						转换后: converted
					});
					
					return converted;
				});
				
				console.log('转换完成，最终数据:', convertedData);
				return convertedData;
			},
			
			// 从优惠信息中提取价格（已废弃，不再使用）
			extractPriceFromMessage(message) {
				// 此方法已废弃，不再提取价格
				return null;
			},
			
			// 切换到地图模式
			async switchToMapMode() {
				this.isMapMode = true;
			},
			
			// 切换到列表模式
			switchToListMode() {
				this.isMapMode = false;
				this.selectedStation = null;
			},
			
			// 返回上一页
			goBack() {
				console.log('点击返回按钮');
				
				// 检查页面栈
				const pages = getCurrentPages();
				console.log('当前页面栈:', pages);
				console.log('页面栈长度:', pages.length);
				
				if (pages.length > 1) {
					// 有上一页，直接返回
					console.log('返回上一页');
					uni.navigateBack({
						delta: 1,
						success: () => {
							console.log('返回成功');
						},
						fail: (err) => {
							console.error('返回失败:', err);
							// 如果返回失败，尝试跳转到首页
							this.goToHome();
						}
					});
				} else {
					// 没有上一页，跳转到首页
					console.log('没有上一页，跳转到首页');
					this.goToHome();
				}
			},
			
			// 跳转到首页
			goToHome() {
				console.log('尝试跳转到首页');
				
				// 首先尝试使用 switchTab（如果首页是 tabBar 页面）
				uni.switchTab({
					url: '/pages/index/index',
					success: () => {
						console.log('switchTab 跳转首页成功');
					},
					fail: (switchErr) => {
						console.error('switchTab 跳转首页失败:', switchErr);
						
						// 如果 switchTab 失败，尝试使用 navigateTo
						uni.navigateTo({
							url: '/pages/index/index',
							success: () => {
								console.log('navigateTo 跳转首页成功');
							},
							fail: (navigateErr) => {
								console.error('navigateTo 跳转首页也失败:', navigateErr);
								
								// 最后的降级方案：显示提示
								uni.showToast({
									title: '返回失败，请手动返回',
									icon: 'none',
									duration: 3000
								});
							}
						});
					}
				});
			},
			
			// 显示更多选项
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['刷新', '设置', '关于'],
					success: (res) => {
						if (res.tapIndex === 0) {
							this.refreshData();
						}
					}
				});
			},
			
			// 刷新数据
			async refreshData() {
				await this.getCurrentLocation();
				await this.loadGasStations();
			},
			
			// 搜索相关方法
			handleInput(e) {
				this.searchKeyword = e.value;
				this.isSearching = !!e.value;
				
				// 防抖搜索
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				this.searchTimer = setTimeout(() => {
					this.performSearch(e.value);
				}, 500);
			},
			
			async handleSearch(e) {
				const keyword = e.value || this.searchKeyword;
				await this.performSearch(keyword);
			},
			
			// 搜索加油站
			async searchGasStations(keyword) {
				try {
					this.loading = true;
					this.isSearching = true;
					
					const result = await gasStationApi.searchGasStations(keyword);
					
					console.log('搜索加油站API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 根据你的request.js，API函数直接接收到{code, msg, data}格式
					if (result.code === 200) {
						this.gasStations = result.data;
					}
				} catch (error) {
					console.error('搜索加油站失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.isSearching = false;
				}
			},
			
			// 显示筛选选项
			showFilterOptions() {
				uni.showActionSheet({
					itemList: ['按距离排序', '按价格排序', '按评分排序'],
					success: (res) => {
						const sortOptions = ['distance', 'price', 'rating'];
						const sortBy = sortOptions[res.tapIndex];
						this.sortStations(sortBy);
					}
				});
			},
			
			// 排序加油站
			async sortStations(sortBy) {
				try {
					if (this.currentLocation) {
						const result = await gasStationApi.getNearbyGasStations(
							this.currentLocation.latitude,
							this.currentLocation.longitude,
							5000
						);
						
						console.log('排序加油站API返回结果:', result);
						console.log('result.code:', result.code);
						console.log('result.data:', result.data);
						console.log('result.msg:', result.msg);
						
						// 根据你的request.js，API函数直接接收到{code, msg, data}格式
						if (result.code === 200) {
							// 对结果进行排序
							this.gasStations = this.sortGasStationsByType(result.data, sortBy);
						}
					}
				} catch (error) {
					console.error('排序加油站失败:', error);
				}
			},
			
			// 根据类型排序加油站
			sortGasStationsByType(stations, sortBy) {
				const sortedStations = [...stations];
				switch (sortBy) {
					case 'distance':
						return sortedStations.sort((a, b) => {
							const distA = parseFloat(a.distance) || 0;
							const distB = parseFloat(b.distance) || 0;
							return distA - distB;
						});
					case 'rating':
						return sortedStations.sort((a, b) => (b.rating || 0) - (a.rating || 0));
					case 'price':
						return sortedStations.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
					default:
						return sortedStations;
				}
			},
			
			// 选择加油站
			selectStation(station) {
				console.log('选择加油站:', station);
				uni.navigateTo({
					url: `/pages/Fuel Nearby/GasStationDetail?id=${station.id}`
				});
			},
			
			// 跳转到加油站详情页
			goToStationDetail(station) {
				if (station) {
					uni.navigateTo({
						url: `/pages/Fuel Nearby/GasStationDetail?id=${station.id}`
					});
				}
			},
			

			
			// 导航到加油站
			navigateToStation(station) {
				console.log('点击导航按钮，加油站信息:', station);
				
				if (!station) {
					console.log('加油站信息为空');
					return;
				}
				
				// 检查加油站坐标
				if (!station.latitude || !station.longitude) {
					console.log('加油站坐标信息缺失');
					uni.showToast({
						title: '加油站坐标信息缺失',
						icon: 'none'
					});
					return;
				}
				
				// 检测当前运行环境
				// #ifdef MP-WEIXIN
				console.log('检测到微信小程序环境');
				// 微信小程序使用微信地图
				uni.openLocation({
					latitude: station.latitude,
					longitude: station.longitude,
					name: station.name,
					address: station.address,
					scale: 18,
					success: () => {
						console.log('微信地图打开成功');
					},
					fail: (err) => {
						console.error('微信地图打开失败:', err);
						// 降级到H5地图
						this.openH5Map(station);
					}
				});
				// #endif
				
				// #ifdef H5
				console.log('检测到H5环境');
				this.openH5Map(station);
				// #endif
				
				// #ifdef APP-PLUS
				console.log('检测到App环境');
				// App环境使用系统地图
				uni.openLocation({
					latitude: station.latitude,
					longitude: station.longitude,
					name: station.name,
					address: station.address,
					scale: 18,
					success: () => {
						console.log('系统地图打开成功');
					},
					fail: (err) => {
						console.error('系统地图打开失败:', err);
						// 降级到H5地图
						this.openH5Map(station);
					}
				});
				// #endif
				
				// 如果没有条件编译，默认使用H5地图
				// #ifndef MP-WEIXIN || H5 || APP-PLUS
				console.log('未检测到特定环境，使用H5地图');
				this.openH5Map(station);
				// #endif
			},
			
			// 打开H5地图
			openH5Map(station) {
				try {
					const mapUrl = `https://uri.amap.com/navigation?to=${station.longitude},${station.latitude},${station.name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`;
					console.log('打开H5地图:', mapUrl);
					
					// #ifdef H5
					window.open(mapUrl, '_blank');
					// #endif
					
					// #ifndef H5
					// 非H5环境，使用plus.runtime.openURL
					if (typeof plus !== 'undefined' && plus.runtime) {
						plus.runtime.openURL(mapUrl);
					} else {
						// 最后的降级方案
						uni.showModal({
							title: '导航提示',
							content: `无法直接打开地图，请手动导航到：${station.name}\n地址：${station.address}`,
							showCancel: false
						});
					}
					// #endif
				} catch (error) {
					console.error('打开H5地图失败:', error);
					uni.showModal({
						title: '导航提示',
						content: `无法打开地图，请手动导航到：${station.name}\n地址：${station.address}`,
						showCancel: false
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fuel-nearby-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 80px;
			display: flex;
			justify-content: space-between;
		}
	}
	
	// 搜索栏作为页面头部
	.search-header {
		padding: 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.search-container {
			margin-bottom: 0;
		}
	}
	
	// 位置信息栏
	.location-info-bar {
		background-color: #f8f9fa;
		padding: 12px 16px;
		margin-bottom: 8px;
		border-bottom: 1px solid #e9ecef;
		
		.location-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.location-left {
				display: flex;
				align-items: center;
				gap: 8px;
				flex: 1;
				
				.location-text {
					font-size: 14px;
					color: #495057;
					font-weight: 500;
				}
			}
			
			.location-actions {
				display: flex;
				align-items: center;
				gap: 12px;
			}
			
			.action-btn {
				font-size: 13px;
				color: #007AFF;
				text-decoration: underline;
				cursor: pointer;
				padding: 4px 8px;
				border-radius: 4px;
				background-color: #e3f2fd;
				transition: all 0.2s ease;
				
				&:hover {
					background-color: #bbdefb;
				}
				
				&:active {
					background-color: #90caf9;
				}
			}
			
			.data-source-icon {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 32px;
				height: 32px;
				border-radius: 50%;
				background-color: #f8f9fa;
				border: 1px solid #e9ecef;
				cursor: pointer;
				transition: all 0.2s ease;
				
				&:hover {
					background-color: #e9ecef;
					transform: scale(1.05);
				}
				
				&:active {
					transform: scale(0.95);
				}
			}
		}
	}
	
	// 模式切换
	.control-section {
		background-color: #ffffff;
		padding: 12px 16px;
		margin-bottom: 8px;
		border-bottom: 1px solid #f0f0f0;
		
		.mode-switch {
			.switch-container {
				display: flex;
				background-color: #f5f5f5;
				border-radius: 8px;
				padding: 4px;
				gap: 4px;
				
				.switch-btn {
					flex: 1;
					text-align: center;
					padding: 8px 12px;
					border-radius: 6px;
					font-size: 14px;
					color: #666;
					background-color: transparent;
					transition: all 0.3s ease;
					cursor: pointer;
					
					&.active {
						background-color: #007AFF;
						color: #ffffff;
						box-shadow: 0 2px 4px rgba(0, 122, 255, 0.3);
					}
					
					&:hover:not(.active) {
						background-color: #e0e0e0;
					}
				}
			}
		}
	}
	
	// 筛选选项
	.filter-section {
		background-color: #ffffff;
		padding: 12px 16px;
		margin-bottom: 12px;
		
		.filter-item {
			display: flex;
			align-items: center;
			gap: 4px;
			
			.filter-text {
				font-size: 14px;
				color: #666666;
			}
		}
	}
	
	// 搜索状态
	.search-status {
		background-color: #ffffff;
		padding: 8px 16px;
		margin-bottom: 12px;
		
		.search-status-text {
			font-size: 12px;
			color: #999999;
		}
	}
	
	// 地图容器
	.map-container {
		height: calc(100vh - 200px);
	}
	
	// 加油站列表
	.station-list {
		.loading-container {
			padding: 40px 0;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		
		.empty-container {
			padding: 60px 0;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.empty-text {
				font-size: 16px;
				color: #999999;
			}
		}
		
		.station-item {
			display: flex;
			background-color: #ffffff;
			margin: 0 16px 12px 16px;
			padding: 16px;
			border-radius: 8px;
			
			.station-image {
				width: 80px;
				height: 60px;
				margin-right: 12px;
				
				.station-img {
					width: 100%;
					height: 100%;
					border-radius: 8px;
				}
			}
			
			.station-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				
				.station-name {
					font-size: 16px;
					font-weight: bold;
					color: #333333;
					margin-bottom: 4px;
				}
				
				.station-price {
					display: flex;
					align-items: center;
					margin-bottom: 4px;
					
					.discount-text {
						font-size: 12px;
						color: #ff4757;
						background-color: #fff5f5;
						padding: 2px 6px;
						border-radius: 4px;
					}
				}
				
				.station-address {
					font-size: 12px;
					color: #999999;
					margin-bottom: 2px;
				}
				
				.station-phone {
					font-size: 11px;
					color: #007AFF;
					margin-bottom: 2px;
				}
				
				.station-time {
					font-size: 11px;
					color: #666666;
				}
			}
			
			.station-actions {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				justify-content: space-between;
				
				.distance {
					font-size: 14px;
					color: #007AFF;
					font-weight: bold;
				}
				
				.navigation-btn {
					width: 32px;
					height: 32px;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #f0f8ff;
					border-radius: 50%;
					cursor: pointer;
					position: relative;
					z-index: 10;
				}
			}
		}
	}
</style>

